<template>
  <div class="food-management">
    <h2 class="page-title">菜品管理</h2>
    
    <!-- 搜索和过滤 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="菜品名称">
          <el-input v-model="searchForm.name" placeholder="请输入菜品名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="菜品分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
            <el-option
              v-for="category in categories"
              :key="category"
              :label="category"
              :value="category">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜品状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="上架" :value="1"></el-option>
            <el-option label="下架" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="searchFoods">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetSearch">重置</el-button>
          <el-button type="success" icon="el-icon-plus" @click="openAddDialog">添加菜品</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 菜品列表 -->
    <el-card class="food-list-card">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="全部菜品" name="all"></el-tab-pane>
        <el-tab-pane label="已上架" name="active"></el-tab-pane>
        <el-tab-pane label="已下架" name="inactive"></el-tab-pane>
      </el-tabs>
      
      <!-- 分类统计 -->
      <div class="category-stats">
        <el-tag 
          v-for="(count, category) in categoryCounts" 
          :key="category"
          :type="searchForm.category === category ? 'primary' : ''"
          effect="plain"
          @click="filterByCategory(category)">
          {{ category }} ({{ count }})
        </el-tag>
      </div>
      
      <!-- 表格 -->
      <el-table
        :data="foodList"
        border
        stripe
        style="width: 100%"
        v-loading="loading">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column label="图片" width="100">
          <template slot-scope="scope">
            <div class="food-image">
              <img :src="scope.row.image" alt="菜品图片" @click="showImagePreview(scope.row.image)">
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="菜品名称" width="150"></el-table-column>
        <el-table-column prop="price" label="价格" width="100">
          <template slot-scope="scope">
            ¥{{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120"></el-table-column>
        <el-table-column prop="sales" label="销量" width="100"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '已上架' : '已下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button 
              size="mini" 
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="toggleFoodStatus(scope.row)">
              {{ scope.row.status === 1 ? '下架' : '上架' }}
            </el-button>
            <el-button size="mini" type="danger" @click="deleteFood(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[5,10, 20, 50, 100]"
          :page-size="pagination.size"
          :current-page="pagination.page"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 添加/编辑菜品对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '添加菜品' : '编辑菜品'"
      :visible.sync="dialogVisible"
      width="500px">
      <el-form :model="foodForm" :rules="foodRules" ref="foodForm" label-width="100px">
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="foodForm.name" placeholder="请输入菜品名称"></el-input>
        </el-form-item>
        
        <el-form-item label="菜品价格" prop="price">
          <el-input-number v-model="foodForm.price" :precision="2" :step="0.1" :min="0" controls-position="right"></el-input-number>
        </el-form-item>
        
        <el-form-item label="菜品分类" prop="category">
          <el-select 
            v-model="foodForm.category" 
            placeholder="请选择分类或输入新分类" 
            style="width: 100%;"
            filterable
            allow-create
            default-first-option
            @change="handleCategoryChange">
            <el-option
              v-for="category in categories"
              :key="category"
              :label="category"
              :value="category">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="菜品图片" prop="image">
          <el-upload
            class="food-image-uploader"
            :action="`${$baseURL}/api/upload/food`"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload">
            <img v-if="foodForm.image" :src="foodForm.image" class="food-image-preview">
            <i v-else class="el-icon-plus food-image-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip">只能上传JPG/PNG文件，且不超过2MB</div>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="菜品描述" prop="description">
          <el-input type="textarea" v-model="foodForm.description" :rows="3" placeholder="请输入菜品描述"></el-input>
        </el-form-item>
        
        <el-form-item label="菜品状态" prop="status">
          <el-radio-group v-model="foodForm.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitFoodForm">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 图片预览 -->
    <el-dialog :visible.sync="previewVisible" title="图片预览" width="50%">
      <img :src="previewImage" alt="预览图片" style="width: 100%;">
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { 
  addFood, 
  updateFood, 
  updateFoodStatus, 
  deleteFood, 
  getFoodsByMerchant, 
  getMerchantFoodCategories,
} from '@/api/food'
import { getMerchantByUserId } from '@/api/merchant'

export default {
  name: 'FoodManagement',
  data() {
    return {
      // 搜索表单
      searchForm: {
        name: '',
        category: '',
        status: ''
      },
      
      // 当前激活的标签
      activeTab: 'all',
      
      // 菜品列表
      foodList: [],
      
      // 加载状态
      loading: false,
      
      // 总记录数
      total: 0,
      
      // 分页信息
      pagination: {
        page: 1,
        size: 5
      },
      
      // 分类列表
      categories: [],
      
      // 分类数量统计
      categoryCounts: {},
      
      // 对话框相关
      dialogVisible: false,
      dialogType: 'add', // add 或 edit
      
      // 菜品表单
      foodForm: {
        id: null,
        merchantId: null,
        name: '',
        price: 0,
        description: '',
        image: '',
        category: '',
        status: 1,
        sales: 0
      },
      
      // 表单验证规则
      foodRules: {
        name: [
          { required: true, message: '请输入菜品名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入菜品价格', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择菜品分类', trigger: 'change' }
        ],
        image: [
          { required: true, message: '请上传菜品图片', trigger: 'change' }
        ]
      },
      
      // 菜品分类相关
      
      // 图片预览
      previewVisible: false,
      previewImage: ''
    }
  },
  created() {
    this.getMerchantId()
    this.loadCategories()
    this.fetchFoodList()
  },
  methods: {
    // 获取商家ID
    getMerchantId() {
      const userId = this.$store.state.user.id
      getMerchantByUserId(userId)
        .then(response => {
          if (response.code === 200) {
            this.foodForm.merchantId = response.data.id
          } else {
            this.$message.error(response.message || '获取商家信息失败')
          }
        })
        .catch(error => {
          console.error('获取商家信息失败', error)
          this.$message.error('获取商家信息失败')
        })
    },
    
    // 加载分类列表
    loadCategories() {
      const merchantId = this.$store.state.user.merchantId || this.foodForm.merchantId
      
      getMerchantFoodCategories(merchantId)
        .then(response => {
          if (response.code === 200) {
            this.categories = response.data || []
          }
        })
        .catch(error => {
          console.error('获取分类列表失败', error)
        })
    },
    
    // 获取菜品列表
    fetchFoodList() {
      this.loading = true
      
      const merchantId = this.$store.state.user.merchantId || this.foodForm.merchantId
      
      // 获取状态过滤条件
      let status = null
      if (this.searchForm.status !== '') {
        status = this.searchForm.status
      } else if (this.activeTab === 'active') {
        status = 1
      } else if (this.activeTab === 'inactive') {
        status = 0
      }
      
      getFoodsByMerchant(merchantId, { status })
        .then(response => {
          if (response.code === 200) {
            // 先获取所有菜品
            let foods = response.data || []
            
            // 根据搜索条件进行本地过滤
            if (this.searchForm.name) {
              foods = foods.filter(food => 
                food.name.toLowerCase().includes(this.searchForm.name.toLowerCase())
              )
            }
            
            if (this.searchForm.category) {
              foods = foods.filter(food => 
                food.category === this.searchForm.category
              )
            }
            
            // 计算分页数据
            this.total = foods.length
            const startIndex = (this.pagination.page - 1) * this.pagination.size
            const endIndex = startIndex + this.pagination.size
            this.foodList = foods.slice(startIndex, endIndex)
            
            // 统计各分类数量
            // this.calculateCategoryCounts()
          } else {
            this.$message.error(response.message || '获取菜品列表失败')
          }
          this.loading = false
        })
        .catch(error => {
          console.error('获取菜品列表失败', error)
          this.$message.error('获取菜品列表失败')
          this.loading = false
        })
    },
    
    // 统计各分类数量
    calculateCategoryCounts() {
      const merchantId = this.$store.state.user.merchantId || this.foodForm.merchantId
      
      axios.get(`/api/foods/category-counts/${merchantId}`)
        .then(response => {
          if (response.code === 200) {
            this.categoryCounts = response.data || {}
          }
        })
        .catch(error => {
          console.error('获取分类统计失败', error)
        })
    },
    
    // 搜索菜品
    searchFoods() {
      this.pagination.page = 1
      this.fetchFoodList()
    },
    
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        name: '',
        category: '',
        status: ''
      }
      this.pagination.page = 1
      this.fetchFoodList()
    },
    
    // 切换标签
    handleTabClick(tab) {
      this.pagination.page = 1
      this.fetchFoodList()
    },
    
    // 按分类筛选
    filterByCategory(category) {
      this.searchForm.category = this.searchForm.category === category ? '' : category
      this.pagination.page = 1
      this.fetchFoodList()
    },
    
    // 每页大小变化
    handleSizeChange(size) {
      this.pagination.size = size
      this.fetchFoodList()
    },
    
    // 页码变化
    handleCurrentChange(page) {
      this.pagination.page = page
      this.fetchFoodList()
    },
    
    // 打开添加对话框
    openAddDialog() {
      this.dialogType = 'add'
      this.foodForm = {
        id: null,
        merchantId: this.$store.state.user.merchantId || this.foodForm.merchantId,
        name: '',
        price: 0,
        description: '',
        image: '',
        category: '',
        status: 1,
        sales: 0
      }
      this.dialogVisible = true
      
      // 在下一个事件循环重置表单验证
      this.$nextTick(() => {
        this.$refs.foodForm && this.$refs.foodForm.clearValidate()
      })
    },
    
    // 打开编辑对话框
    openEditDialog(food) {
      this.dialogType = 'edit'
      this.foodForm = { ...food }
      this.dialogVisible = true
      
      // 在下一个事件循环重置表单验证
      this.$nextTick(() => {
        this.$refs.foodForm && this.$refs.foodForm.clearValidate()
      })
    },
    
    // 提交菜品表单
    submitFoodForm() {
      this.$refs.foodForm.validate((valid) => {
        if (valid) {
          if (this.dialogType === 'add') {
            // 添加菜品
            addFood(this.foodForm)
              .then(response => {
                if (response.code === 200) {
                  this.$message.success('添加菜品成功')
                  this.dialogVisible = false
                  this.fetchFoodList()
                  this.loadCategories()
                } else {
                  this.$message.error(response.message || '添加菜品失败')
                }
              })
              .catch(error => {
                console.error('添加菜品失败', error)
                this.$message.error('添加菜品失败')
              })
          } else {
            // 更新菜品
            updateFood(this.foodForm.id, this.foodForm)
              .then(response => {
                if (response.code === 200) {
                  this.$message.success('更新菜品成功')
                  this.dialogVisible = false
                  this.fetchFoodList()
                } else {
                  this.$message.error(response.message || '更新菜品失败')
                }
              })
              .catch(error => {
                console.error('更新菜品失败', error)
                this.$message.error('更新菜品失败')
              })
          }
        } else {
          return false
        }
      })
    },
    
    // 切换菜品状态
    toggleFoodStatus(food) {
      const newStatus = food.status === 1 ? 0 : 1
      const action = newStatus === 1 ? '上架' : '下架'
      
      this.$confirm(`确定要${action}该菜品吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateFoodStatus(food.id, newStatus, this.foodForm.merchantId)
          .then(response => {
            if (response.code === 200) {
              this.$message.success(`${action}成功`)
              food.status = newStatus
            } else {
              this.$message.error(response.message || `${action}失败`)
            }
          })
          .catch(error => {
            console.error(`${action}失败`, error)
            this.$message.error(`${action}失败`)
          })
      }).catch(() => {
        // 取消操作
      })
    },
    
    // 删除菜品
    deleteFood(food) {
      this.$confirm('确定要删除该菜品吗? 删除后无法恢复!', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        deleteFood(food.id, this.foodForm.merchantId)
          .then(response => {
            if (response.code === 200) {
              this.$message.success('删除成功')
              this.fetchFoodList()
              this.loadCategories()
            } else {
              this.$message.error(response.message || '删除失败')
            }
          })
          .catch(error => {
            console.error('删除菜品失败', error)
            this.$message.error('删除失败')
          })
      }).catch(() => {
        // 取消操作
      })
    },
    
    // 处理分类变化
    handleCategoryChange(value) {
      // 如果是新创建的分类，添加到分类列表中
      if (value && !this.categories.includes(value)) {
        this.categories.push(value)
        this.$message.success('添加新分类成功')
        
        // 这里可以调用API将新分类保存到后端
        // 如果有保存分类的API的话
      }
    },
    
    // 图片上传成功处理
    handleImageSuccess(response, file) {
      if (response.code === 200) {
        this.foodForm.image = response.data.fileUrl
      } else {
        this.$message.error(response.message || '上传图片失败')
      }
    },
    
    // 图片上传前校验
    beforeImageUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      
      return isJPG && isLt2M
    },
    
    // 显示图片预览
    showImagePreview(url) {
      this.previewImage = url
      this.previewVisible = true
    }
  }
}
</script>

<style scoped>
.food-management {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}

.search-card {
  margin-bottom: 20px;
}

.food-list-card {
  margin-bottom: 20px;
}

.category-stats {
  margin: 15px 0;
}

.category-stats .el-tag {
  margin-right: 10px;
  margin-bottom: 10px;
  cursor: pointer;
}

.food-image {
  width: 60px;
  height: 60px;
  overflow: hidden;
  border-radius: 4px;
}

.food-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.food-image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.food-image-uploader:hover {
  border-color: #409EFF;
}

.food-image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.food-image-preview {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}


</style> 